var express = require('express');
var userModel = require('../../modules/userModel')
var md5 = require('md5')

var router = express.Router();

/* GET home page. */
router.get('/reg', function (req, res, next) {
	res.render('auth/reg', {
		title: '登录'
	});

});
router.post('/reg', function (req, res, next) {
	userModel.create({
		...req.body,
		password: md5(req.body.password)
	}).then(data => {
		console.log('添加成功', data)
		res.render('success', {
			message: '注册成功，请返回登录',
			link: '/auth/login'
		})
	}).catch(err => {
		res.render('success', {
			message: '注册失败，请返回登录',
			link: '/auth/login'
		})
	})
});
router.get('/login', function (req, res, next) {
	res.render('auth/login', {
		title: '登录'
	});

});
router.post('/login', function (req, res, next) {
	userModel.findOne({
		username: req.body.username,
		password: md5(req.body.password)
	}).then(data => {
		console.log(data)

		if (data) {
			//添加session
			req.session.username = req.body.username
			req.session._id = data._id

			res.render('success', {
				message: '登录成功',
				link: '/account'
			})
		} else {
			res.send('账号或密码错误')
		}
	}).catch(err => {
		res.send('登录失败，服务器错误')
		console.log(err)
	})
});
router.get('/logout', function (req, res, next) {
	req.session.destroy(() => { //销毁session
		res.redirect('/auth/login')
	})
});

module.exports = router;